#ifndef __LOGGER_HPP__
#define __LOGGER_HPP__

#include <iostream>
#include <ctime>
#include <cstdio>
#include <filesystem> //c++17文件操作
#include <sstream>
#include <fstream>
#include <unistd.h>
#include <memory>
#include <string>
#include "Mutex.hpp"

enum class Loglevel
{
    DEBUG,
    INFO,
    FATAL,
    WARNING,
    ERROR,
};

std::string Loglevel_to_String(Loglevel level)
{
    switch(level)
    {
    case Loglevel::DEBUG:
        return "DEBUG";
    case Loglevel::ERROR:
        return "ERROR";
    case Loglevel::FATAL:
        return "FATAL";
    case Loglevel::INFO:
        return "INFO";
    case Loglevel::WARNING:
        return "WARNING";
    default:
        return "Unknown";
    }
}

//获取当前时间
std::string GetCurrentTime()
{
    time_t curtime = time(nullptr);
    struct tm curtm;
    localtime_r(&curtime, &curtm);

    char buffer[64];
    snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d", 
        curtm.tm_year + 1990,
        curtm.tm_mon + 1,
        curtm.tm_mday,
        curtm.tm_hour,
        curtm.tm_min,
        curtm.tm_sec);
    return buffer;
}

//基类：日志的刷新策略
class LogStrategy
{
public:
    virtual ~LogStrategy() = default;
    virtual void SyncLog(const std::string& logmessage) = 0;
};

// 显示器刷新
class ConsoleLogStrategy : public LogStrategy
{
public:
    ~ConsoleLogStrategy()
    {}

    void SyncLog(const std::string& logmessage) override
    {
        LockGuard lockguard(&_lock);
        std::cout << logmessage << std::endl;
    }
private:
    Mutex _lock;
};

// 文件刷新
const std::string logfiledir = "Log";
static const std::string logfilename = "log.txt";

class FileLogStrategy : public LogStrategy
{
public:
    ~FileLogStrategy()
    {}

    FileLogStrategy(const std::string& dir = logfiledir, const std::string& filename = logfilename)
        :_dir_path_name(dir)
        ,_filename(filename)
    {
        LockGuard lockguard(&_lock);
        if(std::filesystem::exists(_dir_path_name))
        {
            return;
        }
        try
        {
            std::filesystem::create_directories(_dir_path_name);
        }
        catch(const std::filesystem::filesystem_error& e)
        {
            std::cerr << e.what() << "\r\n";
        }
    }

    void SyncLog(const std::string& logmessage) override
    {
        LockGuard lockguard(&_lock);
        std::string filename = _dir_path_name;
        filename += "/";
        filename += _filename;
        std::ofstream out(filename.c_str(), std::ios::app);//头文件<fstream>，c++封装的输出流，app表示append追加模式打开文件流
        if(!out.is_open())
        {
            return;
        }
        out << logmessage << "\n";
        out.close();
    }
private:
    Mutex _lock;
    std::string _dir_path_name;
    std::string _filename; 
};

//获取一条完整的日志
class Logger
{
public:
    Logger()
    {}

    void EnableConsoleLogStrategy()
    {
        strategy = std::make_unique<ConsoleLogStrategy>();
    }
    void EnableFileLogStrategy()
    {
        strategy = std::make_unique<FileLogStrategy>();
    }

    class LogMessage
    {
    public:
        LogMessage(Loglevel level, const std::string &filename, int line, Logger &logger)
        : _curr_time(GetCurrentTime()),
          _level(level),
          _pid(getpid()),
          _filename(filename),
          _line(line),
          _logger(logger)
        {
            std::stringstream ss;
            ss << "[" << _curr_time << "] "
               << "[" << Loglevel_to_String(_level) << "] "
               << "[" << _pid << "] "
               << "[" << _filename << "] "
               << "[" << _line << "]"
               <<  " - ";//将这些以字符串的形式写入ss中
            _loginfo = ss.str();//转换为string类型
        }
        
        template<class T>
        LogMessage& operator<<(const T& info)
        {
            std::stringstream ss;
            ss << info;
            _loginfo += ss.str();
            return *this;
        }

        ~LogMessage()
        {
            if(_logger.strategy)
            {
                _logger.strategy->SyncLog(_loginfo);
            }
        }

    private:
        std::string _curr_time; // 日志时间
        Loglevel _level; // 日志等级
        pid_t _pid; // 进程pid
        std::string _filename;
        int _line;

        std::string _loginfo; // 一条合并完成的，完整的日志信息
        Logger &_logger; // 提供刷新策略的具体做法
    };

    LogMessage operator()(Loglevel level, const std::string &filename, int line)
    {
        return LogMessage(level, filename, line, *this);//返回一个临时对象，让临时对象在析构时帮我们得到需要的日志信息
    }
    ~Logger()
    {

    }
private:
    std::unique_ptr<LogStrategy> strategy;
};

Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define EnableConsoleLogStrategy() logger.EnableConsoleLogStrategy()
#define EnableFileLogStrategy() logger.EnableFileLogStrategy()

#endif